import {Request, UploadFiles} from "../../utils/request";
import host from "../../utils/host";
const HostUrl = host.service;
const Requ = new Request();
const File = new UploadFiles();
var app = getApp();
var change = 0
var spe
var spestate
var datastate
var goodsprice
var imagechange = 0
var goodsid
var groupid
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodslibrary: 9999,
    content: [],
    px: [],
    pxopen: false,
    pxshow: false,
    active: true,
    filePath: '',
    checked: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    goodsid = options.goodsid;
    var that = this;
    
    wx.request({
      url: HostUrl.host + 'get_shopgoods_info.cls.php',
      method: 'POST',
      data: {
        goods_id: goodsid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'cookie': 'PHPSESSID=' + app.globalData.phpsessId
      },
      success: function (res) {
        if (res.data.code == -1) {
          wx.showToast({
            title: '登陆超时',
            icon: 'none',
            duration: 2000,
            mask: true
          })

          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/index/index'
            })
          }, 2000)
        } else {
          if (res.data.switchChange == 1){
            var switch1Checked = true
            spe = new Array()
            spestate = 0
            for(var x=0;x< res.data.goods.spec.length;x++){
                spestate = x
                datastate = 0
                spe[spestate] = new Object()
                spe[spestate].data = new Array()
              for (var y = 0; y < res.data.goods.spec[x].data.length; y++){
                datastate = y
                spe[spestate].name = res.data.goods.spec[x].name
                spe[spestate].state = res.data.goods.spec[x].state
                spe[spestate].data[datastate] = new Object()
                spe[spestate].data[datastate].name = res.data.goods.spec[x].data[y].name
                spe[spestate].data[datastate].money = Number(res.data.goods.spec[x].data[y].price) + Number(res.data.price)
                spe[spestate].data[datastate].price = res.data.goods.spec[x].data[y].price
                spe[spestate].data[datastate].judge = res.data.goods.spec[x].data[y].judge
                spe[spestate].data[datastate].num = 0
                that.setData({
                  spe: spe
                })
              }
              console.log(that.data.spe)
            }
          } else if (res.data.switchChange == 2){
            var switch1Checked = false
          }
          that.setData({
            data: res.data,
            goodsname: res.data.name,
            goodsprice: res.data.price,
            goodsmeal: res.data.packcharge,
            goodslibrary: res.data.stock,
            goodsstyle: res.data.text,
            filePath: HostUrl.HostName + res.data.image,  // 域名 + 图片路径
            groupid: res.data.groupid,
            changes: switch1Checked,
            switchChange: res.data.state,
            MG_id: res.data.id,
          })
          groupid = res.data.groupid 
          // 勾选秒杀按钮         
          if( res.data.seckill_id > 0){
            that.setData({
              checked: true
            });
          }
        }
      }
    })
    wx.request({
      url: HostUrl.host + 'get_shopgroup.cls.php',
      method: 'POST',
      data: {
        data: 0
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'cookie': 'PHPSESSID=' + app.globalData.phpsessId
      },
      success: function (res) {
        if (res.data.code == -1) {
          wx.showToast({
            title: '登陆超时',
            icon: 'none',
            duration: 2000,
            mask: true
          })

          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/index/index'
            })
          }, 2000)
        } else {
          var id = Number(groupid)
          var group_id
          var group_data = new Array()
          for(var i=0; i<res.data.groups.length;i++){
            group_id = res.data.groups[i].id
            group_data[group_id] = new Array()
            group_data[group_id].name = res.data.groups[i].name
            group_data[group_id].type = res.data.groups[i].type
            group_data[group_id].id = res.data.groups[i].id
          }
          
          that.setData({
            data: res.data,
            groupname: group_data[groupid].name,
            groupid: groupid,
            goodstype: group_data[groupid].type
          })
        }
      }
    })
  },

  //商品名
  goodsname: function (e) {
    this.setData({
      goodsname: e.detail.value
    })
  },
  //商品分组选择
  listpx: function (e) {
    if (this.data.pxopen) {
      this.setData({
        pxopen: false,
        pxshow: false,
        active: true,
      })
    } else {
      this.setData({
        content: this.data.px,
        pxopen: true,
        pxshow: false,
        active: false,
      })
    }
  },
  choicegroup: function (e) {
    if (this.data.pxopen) {
      this.setData({
        groupname: e.currentTarget.dataset.groupname,
        groupid: e.currentTarget.dataset.groupid,
        goodstype: e.currentTarget.dataset.type,
        pxopen: false,
        pxshow: false,
        active: true,
      })
    } else {
      this.setData({
        groupname: e.currentTarget.dataset.groupname,
        groupid: e.currentTarget.dataset.groupid,
        goodstype: e.currentTarget.dataset.type,
        pxopen: true,
        pxshow: false,
        active: false,
      })
    }
  },
  //新建分组跳转
  goods_group: function (e) {
    setTimeout(function () {
      wx.navigateTo({
        url: '/pages/goods_group/goods_group'
      })
    }, 200)
  },
  //商品图片上传
  upload: function (e) {
    imagechange = 1
    let arr = new Array();
    wx.chooseImage({
      count: 1, // 一次性最多选择的图片张数，不写默认为9张。
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success:(res)=> {
        // 图片临时路径，可以作为img标签的src属性显示图片
        const filePath = res.tempFilePaths;
        arr = arr.concat(this.data.filePath);
        this.setData({
          filePath: filePath,
          createUploadTask: true,
        });
      },
    })
  },
  //图片预览
  preview: function (e) {
    let arr = new Array();
    arr.push(this.data.filePath);
    wx.previewImage({
      current: e.target.dataset.id,
      urls: arr,
    })
  },
  //商品价格
  goodsprice: function (e) {
    // var value = Number(e.detail.value)
    // goodsprice = value
    this.setData({
      goodsprice: e.detail.value
    })
  },

   // 秒杀价点击 选择事件
   checked: function(e) {
    var check = this.data.checked;
    if (check) {
      this.data.checked = false;
      console.log("已取消选中");
    } else {
      this.data.checked = true;
      console.log("已选中");
    }
    this.setData({
      "checked": this.data.checked,
    });
  },
  //规格开关
  switchChange: function (e) {
    console.log(this.data.groupswitch)
    console.log(e.detail.value)
    if (e.detail.value == true) {
      change++
      this.setData({
        changes: e.detail.value,
        switchChange: 1
      })
      console.log(change)
    } else {
      spe = new Array()
      spestate = 0
      datastate = 0
      spe[spestate] = new Object()
      spe[spestate].name = "规格组名"
      spe[spestate].data = new Array()
      spe[spestate].state = 'true'
      spe[spestate].data[datastate] = new Object()
      spe[spestate].data[datastate].name = "规格名"
      spe[spestate].data[datastate].money = goodsprice
      spe[spestate].data[datastate].price = ""
      spe[spestate].data[datastate].judge = 'true'
      spe[spestate].data[datastate].num = 0
      this.setData({
        spe: spe
      })
      this.setData({
        changes: e.detail.value,
        switchChange: 2
      })
    }
    console.log(change)
    if (change == 1) {
      spe = new Array()
      spestate = 0
      datastate = 0
      spe[spestate] = new Object()
      spe[spestate].name = "规格组名"
      spe[spestate].data = new Array()
      spe[spestate].state = 'true'
      spe[spestate].data[datastate] = new Object()
      spe[spestate].data[datastate].name = "规格名"
      spe[spestate].data[datastate].money = goodsprice
      spe[spestate].data[datastate].price = 0
      spe[spestate].data[datastate].judge = 'true'
      spe[spestate].data[datastate].num = 0
      this.setData({
        spe: spe
      })
    }
  },
  //规格分组增加
  optadd: function (e) {
    if (spestate == 0) {
      spestate++
    } else {
      spestate = e.currentTarget.dataset.z + 1
    }
    datastate = 0
    spe[spestate] = new Object()
    spe[spestate].name = "规格组名"
    spe[spestate].data = new Array()
    spe[spestate - 1].state = false
    spe[spestate].state = 'true'
    spe[spestate].data[datastate] = new Object()
    spe[spestate].data[datastate].name = "规格名"
    spe[spestate].data[datastate].money = goodsprice
    spe[spestate].data[datastate].price = 0
    spe[spestate].data[datastate].judge = 'true'
    spe[spestate].data[datastate].num = 0
    this.setData({
      spe: spe,
      datalength: datastate,
    })
  },
  //规格分组类型增加
  groupadd: function (e) {
    console.log(e.currentTarget.dataset.aa)
    spe = this.data.spe
    spestate = e.currentTarget.dataset.n
    datastate = e.currentTarget.dataset.i + 1
    console.log(spestate)
    console.log(datastate)
    console.log(spe)
    spe[spestate].data[datastate] = new Object()
    spe[spestate].data[datastate].name = "规格名"
    spe[spestate].data[datastate].money = goodsprice
    spe[spestate].data[datastate].price = 0
    spe[spestate].data[datastate - 1].judge = 'false'
    spe[spestate].data[datastate].judge = 'true'
    spe[spestate].data[datastate].num = 0
    this.setData({
      spe: spe,
    })
    console.log(this.data.spe)
  },
  //规格组名插入
  optname: function (e) {
    spestate = e.currentTarget.dataset.optname
    spe[spestate].name = e.detail.value
    this.setData({
      spe: spe,
    })
  },
  //规格名插入
  groupname: function (e) {
    spestate = e.currentTarget.dataset.n
    datastate = e.currentTarget.dataset.i
    spe[spestate].data[datastate].name = e.detail.value
    this.setData({
      spe: spe,
    })
    console.log(spe)
  },
  //规格价格插入
  groupmoney: function (e) {
    spestate = e.currentTarget.dataset.n
    datastate = e.currentTarget.dataset.i
    console.log(e.detail.value)
    var money = Number(e.detail.value)
    spe[spestate].data[datastate].price = money
    var addprice = Number(e.detail.value) + Number(goodsprice)
    spe[spestate].data[datastate].money = addprice
    this.setData({
      spe: spe,
    })
    console.log(spe)
  },
  //规格删除
  groupdelete: function (e) {
    spestate = e.currentTarget.dataset.n
    var i = e.currentTarget.dataset.i
    spe[spestate].data.splice(i, 1)
    this.setData({
      spe: spe,
    })
  },
  //餐盒费
  goodsmeal: function (e) {
    var value = Number(e.detail.value)
    var goodsmeal = value
    console.log(goodsmeal)
    this.setData({
      goodsmeal: goodsmeal
    })
  },
  //商品库存
  goodslibrary: function (e) {
    if (e.detail.value == undefined) {
      var goodslibrary = this.data.goodslibrary
    } else {
      var goodslibrary = e.detail.value
    }
    this.setData({
      goodslibrary: goodslibrary
    })
  },
  //商品风格
  goodsstyle: function (e) {
    this.setData({
      goodsstyle: e.detail.value
    })
  },
  updatagoods: function (e) {
    const img = this.data.filePath
    var imgs = this.data.filePath
    if(this.data.checked==true){
      var seckillchecked = 1
    }else{
      var seckillchecked = -1
    }
    
    var spestate = 1
    console.log(this.data.checked)
    if (this.data.switchChange == 2) {
      var goodsspe = null
    } else {
      var goodsspe = JSON.stringify(this.data.spe)
    }
    if (this.data.switchChange == 1) {
      for (var x = 0; x < spe.length; x++) {
        for (var y = 0; y < spe[x].data.length; y++) {
          console.log(spe[x].data[y].name)
          if (spe[x].name == "") {
            spestate = 0
            break
          } else if (spe[x].data[y].name == "") {
            spestate = 0
            break
          }
          break
        }
        break
      }
    }
    if (this.data.goodsname == undefined) {
      wx.showToast({
        title: '请输入商品名',
        duration: 2000,
        mask: true,
        icon: 'none',
      })
    } else if (imgs == '') {
      wx.showToast({
        title: '请选择商品图片',
        duration: 2000,
        mask: true,
        icon: 'none',
      })
    } else if (spestate == 0) {
      wx.showToast({
        title: '规格不能为空',
        duration: 2000,
        mask: true,
        icon: 'none',
      })
    } else if (this.data.goodsprice == undefined) {
      wx.showToast({
        title: '请输入商品价格',
        duration: 2000,
        mask: true,
        icon: 'none',
      })
    } else if (this.data.goodsmeal == undefined) {
      wx.showToast({
        title: '请输入餐盒费',
        duration: 2000,
        mask: true,
        icon: 'none',
      })
    } else if (this.data.goodstype = 1) {
      const promise = new Promise((resolve, reject)=> {
        new Request('updata_shopgoods.cls.php').request(
          () => {
            return {
              goodsname: this.data.goodsname,
              groupid: this.data.groupid,
              goodsprice: this.data.goodsprice,
              goodsmeal: 1,
              goodslibrary: this.data.goodslibrary,
              goodsstyle: this.data.goodsstyle,
              switchChange: this.data.switchChange,
              goodsspe: goodsspe,
              goodsid:goodsid,
              seckillchecked: seckillchecked
            }
          },
          (res) => {
            res.data.code==1?resolve(res):reject(res);
        });
      });
      promise.then((res)=>{
        if(this.data.createUploadTask){
          let url = HostUrl.host + 'upload_shopgoods.cls.php';
          File.File(url, imgs[0], (data)=>{
            data.code==1?Requ.showToast('修改成功', 'none', ()=>{
              setTimeout(()=>{
                wx.navigateBack({
                  delta: 1
                })
              }, 1800)
            }):Requ.showToast('保存失败');
          }, 'file', ()=>{
            return {
              'MG_id': this.data.MG_id,
            }
          });
          return;
        }
        Requ.showToast('修改成功', 'none', ()=>{
          setTimeout(()=>{
            wx.navigateBack({
              delta: 1
            })
          }, 1800)
        });
      }, ()=>{
        Requ.showToast("修改失败");
      });
      return;
    } else if (this.data.goodstype = 2) {
      wx.request({
        url: HostUrl.host + 'create_shopgoods.cls.php',
        method: 'POST',
        data: {
          goodsname: this.data.goodsname,
          groupid: this.data.groupid,
          goodsmeal: this.data.goodsmeal,
          goodslibrary: this.data.goodslibrary,
          goodsstyle: this.data.goodsstyle,
          seckillchecked: seckillchecked
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'cookie': 'PHPSESSID=' + app.globalData.phpsessId
        },
        success: function (res) {
          if (res.data.code == -1) {
            wx.showToast({
              title: '登陆超时',
              icon: 'none',
              duration: 2000,
              mask: true
            })

            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/index/index'
              })
            }, 2000)
          } else {
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500,
              mask: true
            })
            wx.navigateBack({
              delta: 1
            })
            // if (imagechange ==1){
            //   wx.uploadFile({
            //     url: 'https://apps.zyfuns.com/shop/upload_shopgoods.cls.php',
            //     header: {
            //       'content-type': 'application/x-www-form-urlencoded',
            //       'cookie': 'PHPSESSID=' + app.globalData.phpsessId
            //     },
            //     filePath: img[0],
            //     name: 'file',
            //     formData: {
            //       'user': 'test'
            //     },
            //     success: function (res) {
            //       console.log(res.data.code)
            //       const data = res.data.statusCode
            //       wx.showToast({
            //         title: '图片上传成功',
            //         icon: 'none',
            //         // duration: 2500,
            //         mask: false,

            //       })
            //     },
            //     fail: function (error) {
            //       wx.showToast({
            //         title: '请上传有效照片',
            //         icon: 'none',
            //         duration: 1500,
            //         mask: true,
            //       })
            //     }
            //   })
            // }
          }
        }
      })
    }
  }



})